<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 聚付宝
 */
class JufubaoController extends PayController{
    protected $config;
	protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = [];
        switch($this->config['paytype']) {
            case 1:
            case 2:
                $data['branchId'] = 1006;
                $this->config['gateway'] = 'http://hfzhifu.com/api.php/wxpay/wap_pay';
                break;
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                $data['branchId'] = 1005;
                $this->config['gateway'] = 'http://hfzhifu.com/api.php/alipay/wap_pay';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['merCode'] = $this->config['mch_id'];
        $data['settType'] = 'T0';
        $data['userIp'] = getIP();
        $data['orderId'] = $return['orderid'];
        $data['transAmt'] = intval($return['amount']*100);
        $data['returnUrl'] = $return['notifyurl'];
        $data['notifyUrl'] = $return['callbackurl'];

        $data = array_filter($data);
        $data['signature'] = $this->getSign($data);

        $json = $this->json_encode_ex($data);
        $post['data'] = urlencode(urlencode($json));

        $res = $this->curl_post( $this->config['gateway'],$post);

        echo $res;
    }

    private function json_encode_ex($value){
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {

            $str = json_encode($value);
            $str = preg_replace_callback(
                "#\\\u([0-9a-f]{4})#i",
                function ($matchs) {
                    return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
                },
                $str
            );
            return $str;
        } else {
            return json_encode($value, JSON_UNESCAPED_UNICODE);
        }
    }

    private function curl_post($url, $data = array()) {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //设置获取的信息以文件流的形式返回，而不是直接输出
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
        //执行命令
        $result = curl_exec($curl);
        //关闭url请求
        curl_close($curl);
        return $result;
    }

    private function getSign($data){
        ksort($data);

        $str = '';
        foreach($data as $k=>$v){
            if($v === '' || $v === null || in_array($k,['signature']) || is_array($v)){
                continue;
            }

            $str .= "{$k}={$v}&";
        }

        $str .= $this->config['signkey'];

        return md5($str);
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();
        if(!$this->checkip(getIP(),['159.138.52.119'])){
            exit("wrong");
        }

        $p = I("get.");

        if(!$p || empty($p)){
            exit("wrong");
        }

        foreach($p as $k=>&$v){
            $v = urldecode($v);
        }
        unset($v);

        //获取订单信息
        $orderid = $p['orderId'];

        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['flowId'])
        ));
        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        if($p['transCode'] !== '00'){
            exit("pay fail");
        }
        $sign = $p['signature'];
        $sign2 = $this->getSign($p);

        if($sign !== $sign2){
            echo 'sign_wrong';exit;
        }

        //回调成功
		$this->async($find['pay_orderid'],'OK');
    }

    public function callBackUrl(){

        echo '操作成功'; exit;
    }
}